package Array;

import java.util.Arrays;

public class item17 {
    public static int threeSumClosest(int[] nums, int target) {
        int closest = 0;
        int temp = 0;
        if(nums.length==3)
        {
            return nums[0]+nums[1]+nums[2];
        }
        int min = 10000;
        Arrays.sort(nums);
        boolean flag = false;
        for(int i =0;i<nums.length;i++)
        {
            if(i>nums.length-3){
                break;
            }
            // if(nums[i]==nums[i+1])continue;
            int L = i+1;
            int R = nums.length-1;
            while(L<R)
            {
                closest = nums[i]+nums[L]+nums[R];
                if(closest ==target)
                {
                    flag = true;
                    return closest;
                }
//                min = Math.min(min,Math.abs(target-closest));
               if(Math.abs(target-closest)<min)
               {
                   min = Math.min(min,Math.abs(target-closest));
                   temp =  nums[i]+nums[L]+nums[R];
               }
                
                // while(L<R&&nums[L]==nums[L+1])L++;
                // while(L<R&&nums[R]==nums[R-1])R--;
                if(closest<target)
                {
                    L++;
                }else{
                    R--;
                }


            }
        }
        if(flag==false)
        {
            return temp;
        }else{
            return closest;

        }
    }

    public static void main(String[] args) {
//        [1,1,1,1]
//        4

        int []nums = {-1,2,1,-4};
        int i = threeSumClosest(nums, 1);
        System.out.println(i);

    }
}
